package com.crack;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;

/**
 * @date 2019/10/14
 */
public class Agent implements ClassFileTransformer {


    private final VersionEnum versionEnum;

    public Agent(VersionEnum versionEnum) {
        this.versionEnum = versionEnum;
    }

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {
        try {
            /**
             * 无限试用
             */
            if (className.equals(versionEnum.getClassName())) {
                System.out.println("========== trial ==========");
                System.out.println(className);
                String loadName = className.replaceAll("/", ".");
                CtClass ctClass = ClassPool.getDefault().get(loadName);
                CtMethod ctMethod1 = ctClass.getDeclaredMethod(versionEnum.getExpireStatusMethod());
                ctMethod1.setBody("{return false;}");
                CtMethod ctMethod2 = ctClass.getDeclaredMethod(versionEnum.getDaysRemainingMethod());
                ctMethod2.setBody("{return Integer.MAX_VALUE;}");
                CtMethod ctMethod3 = ctClass.getDeclaredMethod(versionEnum.getProbationaryMethod());
                ctMethod3.setBody("{return Integer.MAX_VALUE;}");

                return ctClass.toBytecode();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classfileBuffer;
    }
}
